package com.zmm.myyimixian.ui.activity.shopping;

import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.zmm.myyimixian.R;
import com.zmm.myyimixian.base.BaseActivity;
import com.zmm.myyimixian.db.Address;
import com.zmm.myyimixian.db.DataDao;
import com.zmm.myyimixian.db.ShoppingCart;
import com.zmm.myyimixian.ui.activity.address.AddressActivity;
import com.zmm.myyimixian.ui.adapter.ModifyCountInterface;
import com.zmm.myyimixian.ui.adapter.ShoppingCartAdapter;
import com.zmm.myyimixian.util.UIManager;
import com.zmm.myyimixian.widget.SelfDialog;

import java.math.BigDecimal;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.listener.DeleteListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

public class ShoppingCartActivity extends BaseActivity implements ModifyCountInterface {
    @BindView(R.id.shopping_rmb_settlement)
    TextView shoppingRmbSettlement;//购物车总金额
    @BindView(R.id.shopping_llayout_settlement)
    LinearLayout shoppingLlayoutSettlement;//结算布局
    @BindView(R.id.address_list_name)
    TextView addressListName;//收货人名字
    @BindView(R.id.address_list_sex)
    TextView addressListSex;//收货人性别
    @BindView(R.id.address_list_phone)
    TextView addressListPhone;//收货人手机号
    @BindView(R.id.address_list_tag)
    TextView addressListTag;//收货人标签
    @BindView(R.id.address_list_detailed)
    TextView addressListDetailed;//收货人详细地址
    @BindView(R.id.address_list_building)
    TextView addressListBuilding;//收货人楼号
    @BindView(R.id.address_list_edit)
    ImageView addressListEdit;//修改地址
    @BindView(R.id.address_llayout_item)
    LinearLayout addressLlayoutItem;//地址布局
    @BindView(R.id.address_null_item)
    LinearLayout addressNullItem;//空地址布局
    private SelfDialog selfDialog;//自定义dialog
    private ShoppingCartAdapter mAdapter;//适配器
    private int ItemCount = 0;//默认购物车0个商品
    private List<ShoppingCart> mList;//购物车数据的集合
    boolean  loadAddressFlag = true;
    Address address;//收货地址对象
    @BindView(R.id.shopping_toolbar)
    Toolbar shoppingToolbar;//toolbar
    @BindView(R.id.shopping_lv)
    ListView shoppingLv;//显示购物车数据的listView
    @BindView(R.id.shopping_llayout_null)
    LinearLayout shoppingLlayoutNull;//listView的空视图
    @BindView(R.id.shopping_progress)
    ProgressBar shoppingProgress;//显示进度的控件
    @BindView(R.id.shopping_error)
    ImageView shoppingError;//网路错误图


    @Override
    protected void initView() {
        shoppingProgress.setVisibility(View.VISIBLE);
        shoppingLlayoutNull.setVisibility(View.GONE);
        mAdapter = new ShoppingCartAdapter();
        shoppingLv.setAdapter(mAdapter);
        shoppingToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mAdapter.setModifyCountInterface(this);//设置接口回调
        //默认不显示收货地址
        addressLlayoutItem.setVisibility(View.GONE);
        addressNullItem.setVisibility(View.GONE);
    }

    //获取购物车数据的方法
    private void loadData() {
        shoppingProgress.setVisibility(View.VISIBLE);
        shoppingError.setVisibility(View.GONE);
        DataDao.getAllShoppingCarts(new FindListener<ShoppingCart>() {
            @Override
            public void onSuccess(List<ShoppingCart> list) {
                shoppingProgress.setVisibility(View.GONE);
                shoppingLlayoutNull.setVisibility(View.VISIBLE);
                shoppingLv.setEmptyView(shoppingLlayoutNull);
                mList = list;
                if (mList.size() > 0) {//有数据的时候显示结算布局
                    shoppingLlayoutSettlement.setVisibility(View.VISIBLE);
                    showMoney();//显示金额
                    loadAddress();//有数据的时候获取收货地址
                } else {//没数据的时候不显示
                    shoppingLlayoutSettlement.setVisibility(View.GONE);
                    addressLlayoutItem.setVisibility(View.GONE);
                    addressNullItem.setVisibility(View.GONE);
                }
                mAdapter.setData(mList);
            }

            @Override
            public void onError(int i, String s) {
                shoppingProgress.setVisibility(View.GONE);
                shoppingLlayoutSettlement.setVisibility(View.GONE);
                shoppingError.setVisibility(View.VISIBLE);
                Toast.makeText(ShoppingCartActivity.this, "网络连接不可用，请检查网络设置", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_shopping_cart;
    }

    @OnClick({R.id.shopping_btn, R.id.shopping_error, R.id.shopping_btn_settlement, R.id.address_llayout_item, R.id.address_null_item})
    public void onClick(View view) {
        Intent intent = new Intent(this, AddressActivity.class);
        intent.putExtra("cart","cart");
        switch (view.getId()) {
            case R.id.shopping_btn:
                UIManager.startMain(ShoppingCartActivity.this);
                break;
            case R.id.shopping_error:
                loadData();//获取数据
                break;
            case R.id.shopping_btn_settlement:
                if (address == null) {
                    Toast.makeText(this, "请选择收货地址", Toast.LENGTH_SHORT).show();
                    return;
                }
                //TODO：跳转到结算界面
                Toast.makeText(this, "跳转到结算界面", Toast.LENGTH_SHORT).show();
                break;
            case R.id.address_llayout_item://选择地址
                startActivityForResult(intent,1);
                break;
            case R.id.address_null_item://选择地址
                startActivityForResult(intent,1);
                break;
        }
    }

    //数量加1
    @Override
    public void doIncrease(final int position, TextView showCountView, ImageButton jian, ImageButton jia, int count) {
        ItemCount = Integer.valueOf(showCountView.getText().toString());
        ++ItemCount;
        final String valueOf = String.valueOf(ItemCount);
        shoppingProgress.setVisibility(View.VISIBLE);//显示进度
        DataDao.setShoppingCart(mList.get(position).getTitle(), valueOf, shoppingProgress, new UpdateListener() {
            @Override
            public void onSuccess() {
                shoppingProgress.setVisibility(View.GONE);//不显示进度
                mList.get(position).setCount(valueOf);
                showMoney();//显示金额
                mAdapter.setData(mList);
            }

            @Override
            public void onFailure(int i, String s) {
                shoppingProgress.setVisibility(View.GONE);//不显示进度
                Toast.makeText(ShoppingCartActivity.this, "当前网络不可用，请检查网络连接", Toast.LENGTH_SHORT).show();
            }
        });

    }

    //数量减1
    @Override
    public void doDecrease(final int position, TextView showCountView, ImageButton jian, ImageButton jia, int count) {
        final String deletname = mList.get(position).getTitle();
        ItemCount = Integer.valueOf(showCountView.getText().toString());
        --ItemCount;
        if (ItemCount < 1) {
            //自定义dialog
            selfDialog = new SelfDialog(ShoppingCartActivity.this);
            selfDialog.setMessage("我真的很好哦~\n确定要删除么？");
            selfDialog.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {
                @Override
                public void onYesClick() {
                    selfDialog.dismiss();
                    shoppingProgress.setVisibility(View.VISIBLE);//显示进度
                    DataDao.deleteShoppingCart(deletname, shoppingProgress, new DeleteListener() {//跟新数据
                        @Override
                        public void onSuccess() {
                            shoppingProgress.setVisibility(View.GONE);//不显示进度
                            mList.remove(position);
                            mAdapter.setData(mList);
                            if (mList.size() > 0) {//有数据的时候显示结算布局
                                shoppingLlayoutSettlement.setVisibility(View.VISIBLE);
                                showMoney();//显示金额
                            } else {//没数据的时候不显示
                                shoppingLlayoutSettlement.setVisibility(View.GONE);
                                addressLlayoutItem.setVisibility(View.GONE);
                                addressNullItem.setVisibility(View.GONE);
                            }
                        }

                        @Override
                        public void onFailure(int i, String s) {
                            shoppingProgress.setVisibility(View.GONE);//不显示进度
                            Toast.makeText(ShoppingCartActivity.this, "当前网络不可用，请检查网络连接", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
            selfDialog.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    selfDialog.dismiss();
                }
            });
            selfDialog.show();


        } else {
            final String text = String.valueOf(ItemCount);
            shoppingProgress.setVisibility(View.VISIBLE);//显示进度
            DataDao.setShoppingCart(deletname, text, shoppingProgress, new UpdateListener() {//跟新数据
                @Override
                public void onSuccess() {
                    shoppingProgress.setVisibility(View.GONE);//不显示进度
                    mList.get(position).setCount(text);
                    showMoney();//显示金额
                    mAdapter.setData(mList);
                }

                @Override
                public void onFailure(int i, String s) {
                    shoppingProgress.setVisibility(View.GONE);//不显示进度
                    Toast.makeText(ShoppingCartActivity.this, "当前网络不可用，请检查网络连接", Toast.LENGTH_SHORT).show();
                }
            });

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();//获取焦点的时候加载网络数据
    }


    private void showMoney() {
        float money = 0;//初始化总金额
        for (int i = 0; i < mList.size(); i++) {
            ShoppingCart shoppingCart = mList.get(i);
            float count = Float.parseFloat(shoppingCart.getCount());
            float price = Float.parseFloat(shoppingCart.getPrice());
            money += count * price;
        }
        //精确到两位小数
        BigDecimal bd = new BigDecimal(money);
        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
        shoppingRmbSettlement.setText(bd + "");
    }

    //加载收货地址
    private void loadAddress() {
        //只加载一次网络数据
        if (!loadAddressFlag) {
            return;
        }
        loadAddressFlag = false;
        DataDao.getAllAddress(new FindListener<Address>() {
            @Override
            public void onSuccess(List<Address> list) {
                if (list.size() > 0) {
                    addressNullItem.setVisibility(View.GONE);
                    addressLlayoutItem.setVisibility(View.VISIBLE);
                    address = list.get(0);
                    boundAddress();
                } else {
                    addressLlayoutItem.setVisibility(View.GONE);
                    addressNullItem.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }

    //绑定收货地址的方法
    private void boundAddress() {
        if (address != null) {
            addressNullItem.setVisibility(View.GONE);
            addressLlayoutItem.setVisibility(View.VISIBLE);
            addressListName.setText(address.getUserName());
            addressListSex.setText(address.getUserSex());
            addressListPhone.setText(address.getUserPhone());
            addressListTag.setText(address.getUserTag());
            addressListDetailed.setText(address.getUserDetailedAddress());
            addressListBuilding.setText(address.getUserBuilding());
            addressListEdit.setImageResource(R.mipmap.ic_arrow_right);
        }else {
            addressNullItem.setVisibility(View.VISIBLE);
            addressLlayoutItem.setVisibility(View.GONE);
        }

    }
    //接受回传的地址
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            address = (Address) data.getSerializableExtra("address");
            boundAddress();
        }
    }
}
